<template>
  <section class="todoapp">
    <!-- 头部部分 -->
    <TodoHeader @addList = "addList"></TodoHeader >

    <!-- 主体部分 -->
    <TodoBody :list = 'renderList'
    :isCheckAll="isCheckAll"
    @delList = "delList" 
    @changeStatus = "changeStatus"
    @changeChecked="changeChecked"
    ></TodoBody>

    <!-- 底部部分 -->
    <TodoFooter 
    :leftListLength = "leftListLength"
    :type = "type"
    :isDoneAll = "isDoneAll"
    @clearDoneList = "clearDoneList"
    @changeType = "changeType"
    v-show = "list.length"
    ></TodoFooter>
  </section>
</template>

<script>
import TodoHeader from '@/components/TodoHeader.vue'
import TodoBody from '@/components/TodoBody.vue'
import TodoFooter from '@/components/TodoFooter.vue'

export default {
  components:{
    TodoHeader,
    TodoBody,
    TodoFooter
  },
  data(){
    return {
      type:'all',
      list: JSON.parse(localStorage.getItem('todoList')) || []
    }
  },
  methods:{
    // 删除
    delList(id){
     this.list = this.list.filter((item)=>item.id !== id)
    },
    // 修改
    changeStatus(id){
    const res = this.list.find((item)=>item.id === id)
    res.isDone = !res.isDone
    },
    // 添加
    addList(value){
      const obj = {
         id: +new Date(), name: value, isDone: false 
      }
      this.list = [...this.list,obj]
    },
    // 清除
    clearDoneList(){
    this.list = this.list.filter((item)=>!item.isDone)
    },
    changeType(type){
      this.type = type
    },
    changeChecked(flag){
      this.list.forEach(item => item.isDone = flag)
    }
  },
  // 计算属性
  computed:{
    leftListLength(){
    return  this.list.filter((item)=>!item.isDone).length
    },
    isDoneAll(){
      return this.list.some((item)=>item.isDone)
    },
    renderList(){
      switch (this.type) {
        case 'all':
          return this.list
          case 'active':
          return this.list.filter((item)=>!item.isDone)
          case 'completed':
          return this.list.filter((item)=>item.isDone) 
        default:
          return this.list
      }
    },
    isCheckAll(){
      return this.list.every(item=>item.isDone)
    }
    
  },
  watch:{
    list:{
      deep:true,
      handler(newVal){
        localStorage.setItem('todoList',JSON.stringify(newVal))
      }
    }
  }
}
</script>

<style></style>
